package com.account.controller;


import com.account.service.AccountService;

import com.account.util.JwtUtil;
import com.account.util.RandomValidateCodeUtil;
import com.entity.Account;


import com.entity.AccountVo;
import com.entity.Authority;
import com.entity.ResultMap;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;


@RestController
public class AccountController {

    @Autowired
    AccountService accountService;


    @RequestMapping("login/{user}")
    public String Login(@PathVariable("user") String user) {
        Account account = new Account();
        account.setUsername(user);
        System.out.println(account);
        return user + "  login";
    }

    @GetMapping("/test")
    public String test() {
        return "test";

    }

    @GetMapping("/vip/test")
    public ResultMap<List<Account>> testvip(String username) {
        ResultMap<List<Account>> resultMap = new ResultMap<>();
        try {
            List<Account> accountList = accountService.getAccountList(username);
            if (accountList != null) {
                resultMap.setCode(200L);
                resultMap.setMessage("查询完成");
                resultMap.setResult(accountList);
            } else {
                resultMap.setCode(-1);
                resultMap.setMessage("查询完成");
            }
        } catch (DataIntegrityViolationException e) {

        }

        return resultMap;
    }

    //
    @RequestMapping("login")
    public ResultMap<AccountVo> Login(Account account) {
        ResultMap<AccountVo> resultMap = new ResultMap<>();
        //通过用户名拿到用户实体类
        Account result = accountService.loginByUserName(account.getUsername());
        AccountVo accountVo = new AccountVo();
        //然后进行密码的加密后的比较
        boolean b = JwtUtil.matchsPassword(account.getPassword(), result.getPassword());
        //如果密码一致表示登录成功
        if (result != null && b) {
            List<Authority> author = accountService.findAuthoritiesByUsername(account.getUsername());
            resultMap.setCode(200L);
            resultMap.setMessage("登录成功");
            //为了给me页面传用户的基本信息
            accountVo.setAccount(result);
            accountVo.setAuthority(author.get(0).getAuthority());
            resultMap.setResult(accountVo);
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), result, author.get(0).getAuthority(), 3600L * 1000);
            resultMap.setToken(token);
        } else {
            resultMap.setCode(-1);
            resultMap.setMessage("登录失败");
        }
        return resultMap;
    }


    @GetMapping("/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {

        //设置响应的类型，告诉浏览器输出的内容是图片
        response.setContentType("image/jpeg");
        //不让浏览器缓存图片
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCodeUtil randomValidateCodeUtil = new RandomValidateCodeUtil();
        randomValidateCodeUtil.getRandomCode(request, response);
    }

    @GetMapping("/checkVerify")
    public boolean checkVerify(String verifycode) {
        if (verifycode.equalsIgnoreCase(RandomValidateCodeUtil.vcode)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 上传头像
     */

    @Value("${file.location}")
   private  String  uploadpath;

    @PostMapping("/uploadavatar")
    public ResultMap<Account> uploadFile(MultipartFile file, int id) {
        ResultMap<Account> resultMap = new ResultMap<>();
        String filename = file.getOriginalFilename();
        String newFileName = UUID.randomUUID() + "-" + filename;//换文件名 防止覆盖
        File filedir = new File(uploadpath);
        if (!filedir.exists()) //首先检查上传的文件夹是否存在
            filedir.mkdirs(); //不存在就直接创建
        try {
            //上传文件 到指定的文件夹下和指定的新的文件名
            file.transferTo(new File(uploadpath + newFileName));
            Account account = new Account();
            account.setId(id);
            account.setAvatar(newFileName);
            accountService.uploadAvatar(account);
            resultMap.setCode(200);
            resultMap.setResult(account);
            resultMap.setMessage("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.setCode(-1);
            resultMap.setMessage("上传失败");
        }
        return resultMap;
    }

    @PostMapping("/testupdate")
    public String testUpdate() {
        return "testUpdate";
    }

}
